package com.mini.util;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.mini.constant.CacheConstants;
import com.mini.redis.RedisCache;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ChannelUtils {

    private static final RedisCache redisCache = SpringUtils.getBean(RedisCache.class);

    /**
     * 根据频道获取关联的用户
     * @param channel
     * @return
     */
    public static Set<String> getChannel(String channel) {

        Set<String> set = new HashSet();

        Set<Object> cacheSet = redisCache.getCacheSet(getChannelKey(channel));
        for (Object o : cacheSet) {
            set.add(o.toString());
        }

        return set;
    }

    /**
     * 根据频道获取关联的用户，去掉重复发送
     * @param channels
     * @return
     */
    public static Set<String> getChannel(List<String> channels) {

        Set<String> set = new HashSet();

        for (String channel : channels) {
            Set<String> cacheSet = getChannel(channel);
            for (String s : cacheSet) {
                set.add(s);
            }
        }

        return set;
    }

    /**
     * 设置用户与频道关联
     *
     * @param request
     */
    public static void setChannel(ServerHttpRequest request) {

        ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;

        HttpServletRequest servletRequest = httpRequest.getServletRequest();

        String[] channels = servletRequest.getParameterValues("channel");

        String loginId = StpUtil.getLoginId().toString();

        if (ObjectUtil.isNotEmpty(channels)) {

            for (String channel : channels) {
                redisCache.addCacheSet(getUserKey(loginId), channel);
                redisCache.addCacheSet(getChannelKey(channel), loginId);
            }
        }

    }


    /**
     * 取消频道关联
     *
     * @param userId
     */
    public static void cancelChannel(String userId) {

        Set<Object> cacheSet = redisCache.getCacheSet(getUserKey(userId));

        for (Object channel : cacheSet) {
            //把频道里面的关联用户踢出
            redisCache.removeCacheSet(getChannelKey(channel.toString()), userId);
        }

        redisCache.deleteObject(getUserKey(userId));
    }

    private static String getUserKey(String userId) {

        return CacheConstants.USER_CHANNEL + userId;
    }

    public static String getUserKeys() {

        return CacheConstants.USER_CHANNEL + "*";
    }

    private static String getChannelKey(String channel) {

        return CacheConstants.CHANNEL_USER + SecureUtil.md5(channel);
    }

    public static String getChannelKeys() {

        return CacheConstants.CHANNEL_USER + "*";
    }

}
